<template>
    <el-upload class="avatar-uploader" :show-file-list="false" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" :http-request="handleUpload">
        <img v-if="imageUrl || imgurl" :src="imageUrl || imgurl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>

<script>
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import AV from "leancloud-storage";
export default {
    props: ["imgurl"],
    data() {
        return {
            imageUrl: "",
        };
    },
    methods: {
        handleUpload(obj) {
            //开发者自己发xhr请求，上传图片
            // console.log("1", obj);
            this.getBase64(obj.file, (base64) => {
                //得到图片的base64编码
                // console.log(base64);
                const data = { base64: base64 };
                // resume.txt 是文件名
                const file = new AV.File("pic.png", data); //将本地的base64转化为leancloud资源
                file.save().then((res) => {
                    //上传图片
                    console.log(res);
                    let { url } = res.attributes;
                    this.imageUrl = url; //预览
                    this.$emit("seturl", url); //传给父级
                });
            });
        },
        handleAvatarSuccess(response, uploadFile) {
            console.log("2", uploadFile);
            // imageUrl.value = URL.createObjectURL(uploadFile.raw);
        },
        beforeAvatarUpload(rawFile) {
            //图片上传前触发
            if (rawFile.type !== "image/jpeg") {
                ElMessage.error("Avatar picture must be JPG format!");
                return false;
            } else if (rawFile.size / 1024 / 1024 > 2) {
                ElMessage.error("Avatar picture size can not exceed 2MB!");
                return false;
            }
            return true;
        },
        getBase64(img, callback) {
            //将本地资源对象，转换为base64编码
            const reader = new FileReader();
            reader.addEventListener("load", () => callback(reader.result));
            reader.readAsDataURL(img);
        },
    },
};
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
